package com.example.blogback.shiro;

import cn.hutool.core.bean.BeanUtil;
import com.example.blogback.entity.User;
import com.example.blogback.jwt.JwtToken;
import com.example.blogback.service.UserService;
import com.example.blogback.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 进行登录或者权限验证的逻辑，自定义Realm
 */
@Slf4j
@Component
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;
    @Autowired
    JwtUtils jwtUtils;

    /**
     * 支持哪种类型的token，这里使用JWT Token
     * 为true会执行下面doGetAuthenticationInfo
     */
    @Override
    public boolean supports(AuthenticationToken token){
        return token instanceof JwtToken;
    }
    @Override
//    授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
//    认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        JwtToken jwt=(JwtToken) token;
        log.info("jwt-------------> {}",jwt);
//        通过jwt获取主体信息
        String userId=jwtUtils.getClaimByToken((String) jwt.getPrincipal()).getSubject();
//        执行业务逻辑
        User user = userService.getById(userId);
        if(user==null){
            throw new UnknownAccountException("账户不存在! ");
        }
        if(user.getStatus()==-1){
            throw new LockedAccountException("账户已被锁定! ");
        }

        AccountProfile profile = new AccountProfile();
        BeanUtil.copyProperties(user,profile);
        return new SimpleAuthenticationInfo(profile,jwt.getCredentials(),getName());


    }
}
